// src/app/[lng]/doc/vue/[team]/route.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import fs from 'fs';
import path from 'path';

export async function GET(request: NextRequest) {
	const { pathname } = new URL(request.url);

	// 提取动态路由参数
	const pathSegments = pathname.split('/').filter(Boolean); // 去除空字符串元素
	const routeParam = pathSegments[pathSegments.length - 1]; // 假设你的动态路由是第三个段

	// 其余的逻辑...
	console.log(`请求参数: ${routeParam}`); // 打印请求参数

	try {
		// 构建一个到子目录的路径
		const childDirPath = path.resolve('public', `file/${routeParam}`);

		// 确保文件路径是绝对路径
		const absolutePath = path.resolve(childDirPath);

		// 检查文件是否存在
		if (!fs.existsSync(absolutePath)) {
			return NextResponse.json({ message: '下载文件出错' }, { status: 200 });
		}

		// 创建文件流
		const filestream = fs.createReadStream(absolutePath);

		// 将文件流转换为 Buffer
		// const chunks = [];
		// for await (const chunk of filestream) {
		// 	chunks.push(chunk);
		// }

		// const buffer = Buffer.concat(chunks);
		// console.log(buffer);

		return new NextResponse(filestream, {
			headers: {
				'Content-Type': 'application/json',
				'content-disposition': routeParam
			},
			status: 200
		});
	} catch (error) {
		console.error('下载文件出错:', error);
		// 返回错误响应
		return NextResponse.json({ message: '下载文件出错' }, { status: 200 });
	}
}
